package com.dwjm.exam.stu_reg;

//import utils.ConnectionDatabaseForMySQLUseJdbc1;
//import utils.ConnectionDatabaseForMySQLUseJdbc1;

import com.dwjm.exam.pojo.Student;
import utils.ConnectionDatabaseForMySQLUseJdbc1;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class StudentDaoImpl implements StudentDao{

    Connection connection = null;
    PreparedStatement pstmt = null;
    ResultSet rest = null;

    public StudentDaoImpl(){
        this.connection = ConnectionDatabaseForMySQLUseJdbc1.getConnection();
    }
    @Override
    public int addStudents(Student student) {
        try {
            // 先检查是否已经存在同名账号
            pstmt = connection.prepareStatement("select studentId from student where username=?");
            pstmt.setString(1, student.getUserName());
            rest = pstmt.executeQuery();
            if (rest.next()) {
                return -1; // 账号已存在
            }

            // 插入新用户
            pstmt = connection.prepareStatement("insert into student(studentId,name,gender,birthDate,idNumber,college,major,className,status,dormId,bedNumber,phone,email,emergencyContact,username,password) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            pstmt.setString(1, student.getStudentId());
            pstmt.setString(2, student.getName());
            pstmt.setString(3, student.getGender());
             pstmt.setDate(4,student.getBirthDate());
            pstmt.setString(5, student.getIdNumber());
            pstmt.setString(6, student.getCollege());
            pstmt.setString(7, student.getMajor());
            pstmt.setString(8, student.getClassName());
            pstmt.setString(9, student.getStatus());
            pstmt.setString(10, student.getDormId());
            pstmt.setString(11, student.getBedNumber());
            pstmt.setString(12, student.getPhone());
            pstmt.setString(13, student.getEmail());
            pstmt.setString(14, student.getEmergencyContact());
            pstmt.setString(15, student.getUserName());
            pstmt.setString(16, student.getPassword());


            int result = pstmt.executeUpdate();

            return result; // 返回影响行数，正常应该是1
        } catch (Exception e) {
            e.printStackTrace();
            return 0; // 发生异常
        }
    }
}
